package megadict.draft.index;

import org.junit.Test;
import static org.junit.Assert.*;

public class StringMatching {

    @Test
    public void testMatchingStringBaseOnByteArray() {

        String content = "đây là chuỗi unicode";

        String string = "là";

        int expectedFoundPos = content.indexOf(string);

        int actualFoundPos = indexOf(content.getBytes(), string.getBytes());

        assertEquals(expectedFoundPos, actualFoundPos);

    }

    @Test
    public void testMatchingStringNotFound() {
        String content = "";

        String string = "Never found me";

        int expectedFoundPos = -1;

        int actualFoundPos = indexOf(content.getBytes(), string.getBytes());

        assertEquals(expectedFoundPos, actualFoundPos);
    }

    @Test
    public void testCopyWithMatchingWord() {
        final String content = "Thử nghiệm Unicode. Copy thử đoạn chuỗi unicode";
        final String stringToCopy = "Copy thử đoạn chuỗi unicode";

        byte[] contentInBytes = content.getBytes();
        byte[] stringInBytes = stringToCopy.getBytes();

        int charToCopy = stringToCopy.length();
        byte[] copyBytes = new byte[charToCopy];

        int firstStringIndex = indexOf(contentInBytes, stringInBytes);
        int endStringIndex = firstStringIndex + charToCopy;
        
        for (int i = firstStringIndex; i < endStringIndex; i++) {
            copyBytes[i - firstStringIndex] = contentInBytes[i];
        }      

        String copyString = new String(copyBytes);
        
        System.out.println(copyString);
    }

    private static int indexOf(byte[] content, byte[] string) {

        int matchedPos = 0;

        for (int i = 0; i < content.length; i++) {
            boolean matched = content[i] == string[matchedPos];
            matchedPos = matched ? matchedPos + 1 : 0;

            if (matchedPos == string.length) {
                return (i + 1) - string.length;
            }
        }

        return -1;
    }
    
    @Test
    public void testStringNaturalOrder() {
        String higher = "00-database-info";
        String smaller = "Black market";
        
        int result = higher.compareTo(smaller);
        boolean greater = result == 1;
        assertTrue(greater);
    }
}
